package com.lzx.lizhenxing.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池的配置类
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExcecutor() {
        // ThreadPoolTaskExecutor
        return new ThreadPoolExecutor(10,
                20,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),
                new ThreadFactory() {  // 自定义线程工厂
                    // 针对Integer的原子类，一般保证高并发情况下，共享的数据不会出问题
                    // AtomicInteger线程安全的对象
                    AtomicInteger v = new AtomicInteger(0);

                    @Override
                    public Thread newThread(Runnable r) {
                        // getAndIncrement()获取值并增加值
                        return new Thread(r, "thread-qfedu-" + v.getAndIncrement());
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

    public static void main(String[] args) {
        AtomicInteger v = new AtomicInteger(0);
        System.out.println(v.getAndIncrement());  // 0
        System.out.println(v.getAndIncrement());  // 1
    }
}
